//
// REPhotoCollectionController.m
// REPhotoCollectionController
//
// Copyright (c) 2012 Roman Efimov (https://github.com/romaonthego)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#import "REPhotoCollectionController.h"
#import "REPhotoThumbnailsCell.h"
//
//#import "MJPhoto.h"
//#import "MJPhotoBrowser.h"

#import "Photo.h"
#import "Config.h"

#import "CameraEngine.h"
#import "PictureManager.h"

@interface REPhotoCollectionController ()<UITableViewDataSource, UITableViewDelegate,REPhotoThumbnailsCellDelegate,CameraEngineDelegate,UIActionSheetDelegate>
{
    int message_type;
    NSString *uuid;
    
    CameraEngine *cameraEngine;
    PictureManager *headManager;
    
    NSString *_lastPicUUID;
    NSInteger _lastPicID;
}
@end

static CGFloat DATEHEADER_HEIGHT  = 30.0;


@implementation REPhotoCollectionController

@synthesize datasource = _datasource;
@synthesize groupByDate = _groupByDate;
@synthesize thumbnailViewClass = _thumbnailViewClass;

- (void)reloadData
{
    if (!_groupByDate) {
        REPhotoGroup *group = [[REPhotoGroup alloc] init];
//        group.month = 1;
//        group.year = 1900;
        [_ds removeAllObjects];
        for (NSObject *object in _datasource) {
            [group.items addObject:object];
        }
        [_ds addObject:group];
        return;
    }

    NSArray *sorted = [_datasource sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSObject <REPhotoObjectProtocol> *photo1 = obj1;
        NSObject <REPhotoObjectProtocol> *photo2 = obj2;
        return ![photo1.date compare:photo2.date];
    }];
    [_ds removeAllObjects];
    for (NSObject *object in sorted) {
        NSObject <REPhotoObjectProtocol> *photo = (NSObject <REPhotoObjectProtocol> *)object;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|
                       NSMonthCalendarUnit |
                       NSYearCalendarUnit fromDate:photo.date];
        NSUInteger month = [components month];
        NSUInteger year  = [components year];
        NSUInteger day   = [components day];
        
        
        REPhotoGroup *group = ^REPhotoGroup *{
            for (REPhotoGroup *group in _ds) {
                
                NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit| NSMonthCalendarUnit |
                                                NSYearCalendarUnit fromDate:group.date];
                NSUInteger group_month = [components month];
                NSUInteger group_year  = [components year];
                NSUInteger group_day   = [components day];
                

                if (group_month == month && group_year == year && group_day ==day)
                    return group;
            }
            return nil;
        }();
        if (group == nil) {
            group = [[REPhotoGroup alloc] init];
            group.date = photo.date;
//            group.month = month;
//            group.year = year;
            [group.items addObject:photo];
            [_ds addObject:group];
        } else {
            [group.items addObject:photo];
        }
    }
    [self.tableView reloadData];
}

-(void)viewDidLoad{
    
    [super viewDidLoad];
    [self setTipInfo];
    
//    self.view.backgroundColor=[UIColor whiteColor];
    singlePicWidth = KPHOTO_SINGLEWIDTH;
    
    _ds = [[NSMutableArray alloc] init];
    self.groupByDate = YES;
    selected_mode=SINGLESELECTED;
    

    CGRect rec = self.view.bounds;
    rec.size.height = self.view.bounds.size.height - self.navigationController.navigationBar.frame.size.height - (OSVersionIsAtLeastiOS7?20:0);
    self.tableView.frame=rec;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    //默认的右键不可点,只有我的相册（MyCloudPhotoViewController）可以点击
    self.titleLabel.text = @"相册详情";
    self.rightBtnPar.userInteractionEnabled=NO;

 }


-(void)setTipInfo{
    noPhotoTip = @"该相册没有照片";
}

/**
 *  获取数据
 */
- (void)getData{
    
    //当前没有任何数据
    if (self.datasource.count == 0) {
        [self addFullloadView];
        [fullloadingView showLoadingState];
        
    }
    
    
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if (![rea isReachable]){
        
        if (fullloadingView) {
            [fullloadingView showErrorMsg:HTTPERROR_CANNOTREACH];
        }else{
            MBALERT(HTTPERROR_CANNOTREACH);
        }
        
        return;
    }
    
    last_timestamp=0;
    _lastPicID = 0;
    _lastPicUUID = @"";
    freshPos = EGORefreshHeader;
//    [self getPhotos];
}

-(void)getMoreData{
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if (![rea isReachable]){
        MBALERT(HTTPERROR_CANNOTREACH);
        return;
    }
    freshPos = EGORefreshFooter;

//    [self getPhotos];
}


-(void)fullloadingViewErrorHandle{
    [fullloadingView.btn addTarget:self action:@selector(selectPicToUpload) forControlEvents:UIControlEventTouchUpInside];
    
}


- (NSDate *)dateFromString:(NSString *)string
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    return [dateFormat dateFromString:string];
}


#pragma mark -
#pragma mark UITableViewController functions



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)atableView
{
    if ([_ds count] == 0) return 0;
    if (!_groupByDate) return 1;
    
    if ([self tableView:self.tableView numberOfRowsInSection:[_ds count] - 1] == 0) {
        return [_ds count] - 1;
    }
    return [_ds count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //四个为一行
    REPhotoGroup *group = (REPhotoGroup *)[_ds objectAtIndex:section];
    NSLog(@"%f", ceil([group.items count] / 4.0f));
    return ceil([group.items count] / 4.0f);
}

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"REPhotoThumbnailsCell";
    REPhotoThumbnailsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[REPhotoThumbnailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier thumbnailViewClass:_thumbnailViewClass];
        cell.deleagte=self;
        cell.backgroundColor=[UIColor whiteColor];
    }
    cell.indexPath = indexPath;
    REPhotoGroup *group = (REPhotoGroup *)[_ds objectAtIndex:indexPath.section];
    
    NSInteger startIndex = indexPath.row * 4;
    NSInteger endIndex   = startIndex + 4;
    if (endIndex > [group.items count])
        endIndex = [group.items count];
    
    [cell removeAllPhotos];
    for (NSInteger i = startIndex; i < endIndex; i++) {
        NSObject <REPhotoObjectProtocol> *photo = [group.items objectAtIndex:i];
        [cell addPhoto:photo];
    }
    [cell refresh];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return !_groupByDate ? 0 : DATEHEADER_HEIGHT;
}

- (UIView *)tableView:(UITableView *)atableView viewForHeaderInSection:(NSInteger)section;  {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 30)];
    view.backgroundColor=[UIColor whiteColor
                           ];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, self.tableView.frame.size.width, 30)];
    label.font = [UIFont systemFontOfSize:14];
    label.backgroundColor=[UIColor whiteColor
                           ];
    
    REPhotoGroup *group = (REPhotoGroup *)[_ds objectAtIndex:section];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *resultString = [dateFormatter stringFromDate:group.date];
    label.text=resultString;
    [view addSubview:label];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 5)];
    return view;
}



-(void)didSelected:(NSInteger)photoGroupIndex thumbnail:(NSInteger)thumbIndex thumbImgView:(UIImageView*)imgview{
    

}

 
#pragma mark -
#pragma mark Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return singlePicWidth + 4;
}


-(void)navRightAction{
    
    if(selected_mode == MUTIBLESELECTED){
        //从编辑模式进入到普通模式
        [self enterNormalMode];
    }else{
        //打开管理
        [self enterManageMode];
    
    }

}

-(void)enterNormalMode{
    [self.rightBtnPar setTitle:@"管理" forState:UIControlStateNormal];
    selected_mode = SINGLESELECTED;
    //卸载“删除”按钮
    if(delBtn){
        [delBtn removeFromSuperview];
        delBtn=nil;
    }
    
    CGRect rec = self.tableView.frame;
    rec.size.height += 55;
    self.tableView.frame=rec;
    
    for (Photo *photo in mutipleSelectedArray) {
        photo.inMutilpleSelected = NO;
    }
    
    [mutipleSelectedArray removeAllObjects];
    
    [self.tableView reloadData];
}

/**
 *  进入管理模式，包含上传、删除。子类根据情况处理
 */
-(void)enterManageMode{

    UIActionSheet *actionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"上传照片",@"编辑", nil];
    [actionsheet showInView:self.view];
    actionsheet.tag = 100;
    
}

/**
 *  进入编辑模式，包含多选删除。子类根据情况处理
 */
-(void)enterEditMode{
    //进入删除模式，多选模式
    selected_mode = MUTIBLESELECTED;
    [self.rightBtnPar setTitle:@"取消" forState:UIControlStateNormal];
    
    CGRect rec = self.tableView.frame;
    rec.size.height -= 55;
    self.tableView.frame=rec;
    
    if (!delBtn) {
        delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [delBtn setFrame:CGRectMake(10, self.view.frame.size.height - 55, self.view.frame.size.width-20, 48)];
        [delBtn setBackgroundImage:[UIImage resizableImage:@"darkbtn_long"] forState:UIControlStateNormal];
        [self.view addSubview:delBtn];
        [delBtn setTitle:@"删除" forState:UIControlStateNormal];
        [delBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [delBtn addTarget:self action:@selector(delAlert:) forControlEvents:UIControlEventTouchUpInside];
        delBtn.userInteractionEnabled=NO;
        
    }

    mutipleSelectedArray = [NSMutableArray array];
}

-(void)delAlert:(id)sender{
    if (mutipleSelectedArray.count == 0) {
        MBALERT(@"请选择至少一张照片");
        return;
    }
    
    NSString *msg = [NSString stringWithFormat:@"确定要删除这%@张照片吗", @(mutipleSelectedArray.count)];
    
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:nil message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消",@"删除", nil];
    [alert show];
    alert.tag = 300;
}



#pragma mark - delete photos


#pragma mark - Camera

-(void)openCameraTakePhoto{
    if (!cameraEngine) {
        cameraEngine = [[CameraEngine alloc]init];
        cameraEngine.delegate=self;
    }
    
    [cameraEngine startCameraTakePhoto:self];
}

-(void)openPhotoAlbum{
    if (!cameraEngine) {
        cameraEngine = [[CameraEngine alloc]init];
        cameraEngine.delegate=self;
    }
    
    [cameraEngine openPhotoAlbum:self editable:NO];
}

-(void)CameraDidTakePhotoFinished:(UIImage *)_img{
    UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
    hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText=@"照片上传中";

    if(_img){
        [self uploadPic:_img];
    }
        
}

-(void)CameraDidChosePhotoFromAlbum:(UIImage *)_img{
    UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
    hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText=@"照片上传中";

    if(_img){
        [self uploadPic:_img];
    }
}


-(void)selectPicToUpload{
    UIActionSheet *actionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    [actionsheet showInView:self.view];
    actionsheet.tag = 200;
    
}




#pragma mark -
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 100 ) {
        if (buttonIndex == 0) {
            
            UIActionSheet *actionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
            [actionsheet showInView:self.view];
            actionsheet.tag = 200;
            
        }else if (buttonIndex == 1) {
            [self enterEditMode];
        }
    }else if (actionSheet.tag == 200 ){
        
        if(mutiplePic){
            [mutiplePic removeAllObjects];
        }
        
        if(buttonIndex == 0){
            [self openCameraTakePhoto];
        }else if(buttonIndex == 1){
            [self openPhotoAlbum];
        }
    }
}

#pragma mark - 上传照片

-(void)showUploadMBView:(int)index{
    if(!hud){
        UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
        hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        NSString *text = @"照片上传中";
//        if (mutiplePic.count != 1 ){
//            text  = [text stringByAppendingFormat:@"(%@/%@)", @(index++), @(mutiplePic.count)];
//         }
        hud.labelText=text;
    }
}



#pragma mark - PictureManagerDelegate

//本地删除
-(void)memoryDelete:(NSArray *)array{
    //删除数据
    [self removeFromDataSource:array];
    [mutipleSelectedArray removeAllObjects];
    
    //重载
    [self reloadData];
}

-(void)pictureDidDelete:(BOOL)success{
    
    if (success) {
        hud.mode=MBProgressHUDModeText;
        hud.labelText=@"照片删除成功";
        [hud hide:YES afterDelay:0.5];
        
        [self memoryDelete:mutipleSelectedArray];
        
        [self enterNormalMode];

        
    }else{
        hud.mode=MBProgressHUDModeText;
        hud.labelText=@"照片删除失败";
        [hud hide:YES afterDelay:0.5];
    }

    
    NSLog(@"pictureDidDelete");
    [delBtn setBackgroundImage:[UIImage resizableImage:@"darkbtn_long"] forState:UIControlStateNormal];
    
    delBtn.userInteractionEnabled = NO;
    [self getData];
}


-(void)pictureDidUploadFinished:(BOOL)success picUrl:(NSString *)url index:(int)uploadIndex{
    
        NSInteger showIndex = uploadIndex+1;

        if (success) {
            
            //多张照片
            if ([mutiplePic count] > 1) {
                
                
                NSString* text  = [NSString stringWithFormat:@"照片上传成功(%@/%@)", @(showIndex), @(mutiplePic.count)];
                NSLog(@"text=%@", text);
                hud.mode=MBProgressHUDModeText;
                hud.labelText=text;
                
                if(showIndex >= mutiplePic.count){
                    [hud hide:YES];
                    [self getData];
                }
                
   
            }else{
                //单张照片
                
                hud.mode=MBProgressHUDModeText;
                hud.labelText=@"照片上传成功";
                [hud hide:YES afterDelay:0.5];
                
                [self getData];
 
            }
        }else{
            if ([mutiplePic count] == 1) {
                hud.mode=MBProgressHUDModeText;
                hud.labelText=@"照片上传失败";
                [hud hide:YES afterDelay:0.5];
            }else{
                NSString* text  = [NSString stringWithFormat:@"照片上传失败(%@/%@)", @(showIndex), @(mutiplePic.count)];
                hud.mode=MBProgressHUDModeText;
                hud.labelText=text;
                [hud hide:YES afterDelay:0.5];

                //说明多张上传的照片，其中有成功上传的照片
                if(uploadIndex>0){
                    [self getData];
                }
            }
        }

    
  }


-(void)removeFromDataSource:(NSArray *)array{
    
    for (int j=0; j<array.count; j++) {
        Photo *delPhoto = array[j];
        
        for (int i=0; i<self.datasource.count; i++) {
            Photo *photo = self.datasource[i];
            
            if ([delPhoto.uuid isEqualToString:photo.uuid]) {
                [self.datasource removeObjectAtIndex:i];
                break;
            }
            
        }
    }
    

    
}

@end
